package de.ds.codematurity.internal;

import java.io.InputStream;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathFactory;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLColorLoader {

	private XPath xpath;
	private Document xmlDom;

	public XMLColorLoader(InputStream inStream) {
		try {

			xpath = XPathFactory.newInstance().newXPath();
			DocumentBuilder db = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();
			xmlDom = db.parse(inStream);
		} catch (Exception e) {
			System.out.println("Error Reading Config File");
			e.printStackTrace();
		}
	}

	public void addColors(List<CodeMaturityColor> list) {
		try {
			/*
			 * FIXME: Doubled Code because attribute reading didn't work.
			 */
			NodeList nodelist = (NodeList) xpath.evaluate(
					"//Color/name[@ignorecase='true']", xmlDom,
					XPathConstants.NODESET);
			if (nodelist == null) {
				throw new RuntimeException();
			}
			for (int i = 0; i < nodelist.getLength(); i++) {
				Node n = nodelist.item(i).getParentNode();
				int red = Integer.parseInt(n.getAttributes()
						.getNamedItem("red").getTextContent());
				int green = Integer.parseInt(n.getAttributes().getNamedItem(
						"green").getTextContent());
				int blue = Integer.parseInt(n.getAttributes().getNamedItem(
						"blue").getTextContent());

				Color color = new Color(Display.getDefault(), red, green, blue);
				String codeString = nodelist.item(i).getTextContent();
				list.add(new CodeMaturityColor(color, codeString, true));
			}

			nodelist = (NodeList) xpath.evaluate(
					"//Color/name[@ignorecase='false']", xmlDom,
					XPathConstants.NODESET);
			if (nodelist == null) {
				throw new RuntimeException();
			}
			for (int i = 0; i < nodelist.getLength(); i++) {
				Node n = nodelist.item(i).getParentNode();
				int red = Integer.parseInt(n.getAttributes()
						.getNamedItem("red").getTextContent());
				int green = Integer.parseInt(n.getAttributes().getNamedItem(
						"green").getTextContent());
				int blue = Integer.parseInt(n.getAttributes().getNamedItem(
						"blue").getTextContent());

				Color color = new Color(Display.getDefault(), red, green, blue);
				String codeString = nodelist.item(i).getTextContent();
				list.add(new CodeMaturityColor(color, codeString, false));
			}

		} catch (Exception e) {
			System.out.println("Error Reading Config File");
			e.printStackTrace();
		}

	}
}
